import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import rcParams
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib.dates as mdates

from scipy.stats import norm
import matplotlib.ticker as ticker

from matplotlib.font_manager import FontProperties
from matplotlib.ticker import FuncFormatter
from datetime import datetime

import matplotlib.gridspec as gridspec

# plt.style.use('seaborn-notebook')


x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 2, 3, 4, 5, 6, 7]



# config = {
#     "font.family": 'serif',  # 衬线字体
#     "font.size": 15,  # 相当于小四大小
#     "font.serif": ['SimHei'],  # 宋体
#     "mathtext.fontset": 'stix',  # matplotlib渲染数学字体时使用的字体，和Times New Roman差别不大
#     'axes.unicode_minus': False  # 处理负号，即-号
# }
# rcParams.update(config)
rcParams['font.sans-serif'] = ['SimHei']  # 中文为宋体
rcParams['font.serif'] = ['Times New Roman']  # 英文为新罗马
rcParams['axes.unicode_minus'] = False  # 正常显示负号
rcParams['font.size'] = 15  # 设置字号

##########################################################################
# 新建figure
fig=plt.figure(constrained_layout=True)  # 可以调整图表大小

#Gridspec()可以跨网格位置来显示子图，通过修改add_subplot()函数来改变。
#projection--功能：子图的投影类型
# grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)

spec=plt.GridSpec(1,1,figure=fig)
labels=['A','B','C','D','E','F','G']
ax1=fig.add_subplot(spec[0,0])
# ax1.bar(x, y,label='A1')
ax1.bar(x,y,width=0.55,label='A1',align = "center", tick_label = labels, ec = 'gray',zorder=10)
#hatch=’/‘定义柱图的斜纹填充，省略该参数表示默认不填充;  ec边框颜色为灰色。

# 在每个柱子上方添加值
for i in range(0,len(x)):
    ax1.text(x[i], y[i], y[i], ha='center', va='bottom')



# 添加网格线，并自定义样式
ax1.grid(linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
ax1.set(xlabel='x轴标题',
        ylabel='y轴标题',
        ) # 设置横纵轴标签与图像标题
ax1.set_title('标题', fontsize=16,x=0.5,y=-0.2)
# plt.subplots_adjust(left=0.125, right=0.9, top=0.9, bottom=0.15)
ax1.set_ylim(0,8)
plt.show()

# plt.savefig('chart.png', bbox_inches='tight', pad_inches=0.02)
# #pad_inches设置图片的留白大小



###################################################################
#多柱状图--横向
# #同方向共用坐标轴
# import numpy as np
# import matplotlib.pyplot as plt
# fig,ax = plt.subplots(2,3,sharex='col',sharey='row')
# print(ax)
# plt.show()

# coding=utf-8
# 散点图的描绘（plt.bar）
df_plot=pd.DataFrame()
x = ["2022-03-04 11:00:00", "2022-03-04 11:01:00", "2022-03-04 11:02:00", "2022-03-04 11:03:00", "2022-03-04 11:04:00"]
df_plot['dt'] = pd.to_datetime(x)

y_3 = [12, 25, 15, 10, 15]
y_2 = [14, 35, 35, 15, 20]
y_1 = [16, 45, 55, 25, 25]

bar_wight = 0.2
y_11 = range(len(y_1))
y_12 = [i+bar_wight for i in y_11]
y_13 = [i+bar_wight*2 for i in y_11]

plt.figure(figsize=(16, 8), dpi=80)
grid = plt.GridSpec(2, 3, wspace=0.2, hspace=0.3)
ax_main = plt.subplot(grid[:,:])

# 绘制条形图
ax_main.barh(range(len(y_11)), y_1, height=bar_wight, label="host1")   # 横形图
ax_main.barh(y_12, y_2, height=bar_wight, label="host2")   # 横形图
ax_main.barh(y_13, y_3, height=bar_wight, label="host3")   # 横形图

# 添加描述信息
ax_main.set_xlabel("流量")
ax_main.set_ylabel("时间")
ax_main.set_title("流量变化")


ax_main.set_yticks(y_12, df_plot['dt'].dt.strftime('%H:%M:%S\n%Y-%m-%d'))
# ax_main.yaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S\n%Y-%m-%d'))

ax_main.grid(linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层




ax_main.legend()
plt.show()




###################################################################
#多柱状图--竖向
# #同方向共用坐标轴
# import numpy as np
# import matplotlib.pyplot as plt
# fig,ax = plt.subplots(2,3,sharex='col',sharey='row')
# print(ax)
# plt.show()

# coding=utf-8
# 散点图的描绘（plt.bar）
df_plot=pd.DataFrame()
x = ["2022-03-04 11:00:00", "2022-03-04 11:01:00", "2022-03-04 11:02:00", "2022-03-04 11:03:00", "2022-03-04 11:04:00"]
df_plot['dt'] = pd.to_datetime(x)

y_3 = [12, 25, 15, 10, 15]
y_2 = [14, 35, 35, 15, 20]
y_1 = [16, 45, 55, 25, 25]

bar_wight = 0.2
y_11 = range(len(y_1))
y_12 = [i+bar_wight for i in y_11]
y_13 = [i+bar_wight*2 for i in y_11]

plt.figure(figsize=(16, 8), dpi=80)
grid = plt.GridSpec(2, 3, wspace=0.2, hspace=0.3)
ax_main = plt.subplot(grid[:,:])

# 绘制条形图
ax_main.bar(range(len(y_11)), y_1,  width=bar_wight, label="host1")   # 横形图
ax_main.bar(y_12, y_2,  width=bar_wight, label="host2")   # 横形图
ax_main.bar(y_13, y_3,  width=bar_wight, label="host3")   # 横形图

# 添加描述信息
ax_main.set_ylabel("流量")
ax_main.set_xlabel("时间")
ax_main.set_title("流量变化")


ax_main.set_xticks(y_12, df_plot['dt'].dt.strftime('%H:%M:%S\n%Y-%m-%d'))
# ax_main.yaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S\n%Y-%m-%d'))

ax_main.grid(linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层

# 在每个柱子上方添加值
for i in range(0,len(y_11)):
    ax_main.text(y_12[i], y_2[i], y_2[i], ha='center', va='bottom')

ax_main.legend()
plt.show()




########################################################
#上下双向的柱状图

df_plot=pd.DataFrame()
x = ["2022-03-04 11:00:00", "2022-03-04 11:01:00", "2022-03-04 11:02:00", "2022-03-04 11:03:00", "2022-03-04 11:04:00"]
df_plot['dt'] = pd.to_datetime(x)

n = len(x)
X = x
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

plt.bar(X, +Y1)
plt.bar(X, -Y2)

for x, y in zip(X, Y1):
    plt.text(x + 0.05, y + 0.05, '%.2f' % y, ha='center', va='bottom')

for x, y in zip(X, Y2):
    plt.text(x + 0.05, -y - 0.15, '%.2f' % y, ha='center', va='bottom')

plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())

plt.show()



